package com.example.AiLangLearn.asr;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.AiLangLearn.R;
import com.iflytek.sparkchain.core.asr.ASR;
import com.iflytek.sparkchain.core.asr.AsrCallbacks;
import com.iflytek.sparkchain.core.asr.AudioAttributes;
import com.iflytek.sparkchain.core.asr.Segment;
import com.iflytek.sparkchain.core.asr.Transcription;
import com.iflytek.sparkchain.core.asr.Vad;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;

public class AsrCnDemoActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "AEELog";
    private TextView tv_asr_cn_result;
    private ASR asr;

    AsrCallbacks mAsrCallbacks = new AsrCallbacks() {
        @Override
        public void onResult(ASR.ASRResult asrResult, Object o) {
            String result = asrResult.getBestMatchText();
            int status = asrResult.getStatus();
            String sid     = asrResult.getSid();
            List<Vad> vads = asrResult.getVads();
            List<Transcription> transcriptions = asrResult.getTranscriptions();
            int vad_begin = -1;
            int vad_end = -1;
            String word = null;
            for(Vad vad:vads){
                vad_begin = vad.getBegin();
                vad_end = vad.getEnd();
            }
            for(Transcription transcription : transcriptions){
                List<Segment> segments = transcription.getSegments();
                for(Segment segment:segments){
                    word = segment.getText();
                }
            }
            String resultBuf = "onResult:{result:"+result+",status:"+status+",begin:"+vad_begin+",end:"+vad_end+",word:"+word+"}";
            Log.d(TAG,resultBuf);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_asr_cn_result.append(resultBuf);
                }
            });
        }

        @Override
        public void onError(ASR.ASRError asrError, Object o) {
            int errCode   = asrError.getCode();
            String errMsg = asrError.getErrMsg();
            String sid    = asrError.getSid();
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asr_cn);
        initView();
        initASR();
    }
    private void initView(){
        findViewById(R.id.asr_btn_sptrans_cn).setOnClickListener(this);
        findViewById(R.id.asr_btn_cancel_cn).setOnClickListener(this);
        tv_asr_cn_result = findViewById(R.id.asr_tv_result_cn);
    }

    private void initASR(){
        asr = new ASR("zh_cn","slm","mandarin");
        asr.registerCallbacks(mAsrCallbacks);
    }

    private int testAsr() {
        int ret = -1;
        if(asr == null){
            Log.d(TAG, "Asr 初始化失败。");
            return ret;
        }
        AudioAttributes atr = new AudioAttributes();
        atr.setSampleRate(16000);
        atr.setEncoding("raw");
        atr.setChannels(1);
        ret = asr.start(atr, null);
        if (ret != 0) {
            Log.e(TAG, "asr start failed" + ret);
            return ret;
        }
        try{
            byte[] data = readStream("/sdcard/iflytek/asr/cn.pcm");
            int leftAudioBytes = data.length;
            int byteWrites = 1280;
            int writeLen = 0;
            int index = 0;

            while (leftAudioBytes > 0) {
                if (leftAudioBytes > byteWrites) {
                    writeLen = byteWrites;
                } else {
                    writeLen = leftAudioBytes;
                }
                leftAudioBytes -= writeLen;
                byte[] part = Arrays.copyOfRange(data, index * byteWrites,
                        index * byteWrites + writeLen);

                ret = asr.write(part);
                if (ret != 0) {
                    Log.e(TAG, "asr write failed" + ret);
                    return ret;
                }
                index++;
            }
            ret = asr.stop(false);//不报错结束
        }catch(Exception e){
            e.printStackTrace();
            ret = asr.stop(true);//报错打断
        }
        if (ret != 0) {
            Log.e(TAG, "asr stop failed" + ret);
            return ret;
        }
        return ret;
    }
    public byte[] readStream(String filePath) throws Exception {
        FileInputStream fs = new FileInputStream(filePath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }
    private void cancel(){
        if(asr!=null)
            asr.stop(true);//报错打断
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(asr!=null)
            asr.stop(true);//报错打断
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.asr_btn_sptrans_cn:
                testAsr();
                break;
            case R.id.asr_btn_cancel_cn:
                cancel();
                break;
        }
    }
}
